package com.example.demo.controller.admin;

import com.example.demo.Util.Result;
import com.example.demo.Util.ResultUtil;
import com.example.demo.mapper.StudentMap;
import com.example.demo.mapper.UserMap;
import com.example.demo.po.Student;
import com.example.demo.po.Teacher;
import com.example.demo.po.dto.StudentAddParam;
import com.example.demo.po.dto.StudentParam;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    StudentMap studentMap;
    @Autowired
    UserMap userMap;

    @Autowired
    StudentService studentService;

    @PostMapping("/save")
    public Result SaveStudent(@RequestBody StudentAddParam student){
        System.out.println(student.toString());

       if(student== null){
           ResultUtil.fail("Null Exception");
       }

      Result res =   studentService.SaveStudentByAdd(student);

       return res;
    }

    @GetMapping("/delete")
    public Result DeleteStudent(@RequestParam("id") int id){
        System.out.println(id);
       int userid = studentMap.GetUserId(id);
       userMap.DeleteUserById(userid);
       studentMap.DeleteStudent(id);

       return ResultUtil.success("删除成功");
    }

    @PostMapping("/update")
    public Result UpdateStudent(@RequestBody StudentParam student){
        if(student== null){
            ResultUtil.fail("Null Exception");
        }

       Result result =  studentService.UpdateStudent(student);

        return result;
    }

    @GetMapping("/get")
    public Result GetStudentList(){

       List<Student> studentList = studentMap.GetStudentList();
       return ResultUtil.success(studentList);
    }

    @GetMapping("/search")
    public Result SearchStudent(@RequestParam(required = false,defaultValue = "") String name,@RequestParam(required = false,defaultValue = "-1") int id){

        if(StringUtils.isEmpty(name) && id==-1){
            return ResultUtil.success(studentMap.GetStudentList());
        }
        List<Student> list =    studentService.SearchStudent(name,id);

        return ResultUtil.success(list);
    }



    @GetMapping("/getStudent")
    public Result GetStudent(@RequestParam("userid") int userid){

        return ResultUtil.success(studentMap.GetStudentByUserId(userid));
    }
}
